
const {
    SyncHook,
    AsyncSeriesHook
} = require('tapable');

class Car {
    constructor() {
        this.hooks = {
            accelerate: new SyncHook(['newspeed']),
            brake: new SyncHook(),
            calculateRoutes: new AsyncSeriesHook(["source", "target", "routesList"])
        }
    }
}

const myCar = new Car();

myCar.hooks.brake.tap("WarningLampPlugin", () => {
    console.log('WarningLampPlugin')
});

myCar.hooks.accelerate.tap('LoggerPlugin', newSpeed => {
    console.log(`Accelerating to ${newSpeed}`);
});

myCar.hooks.calculateRoutes.tapPromise('calculateRoutes tapPromise', (source, target, routesList, callback) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log(`tapPromise to ${source} ${target} ${routesList}`);
            resolve();
        }, 1000);
    });
});

myCar.hooks.brake.call();
myCar.hooks.accelerate.call(10);

console.time('cost')

// https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
// p.then(onFulfilled[, onRejected]);
myCar.hooks.calculateRoutes
    .promise('Async', 'hook', 'demo')
    .then(() => {
        console.timeEnd('cost');
    }, err => {
        console.error(err);
        console.timeEnd('cost');
    });


